package com.peanut.web.util.ocs;

import javax.servlet.http.HttpServletRequest;

import com.peanut.model.user.User;
import com.peanut.util.StringUtil;
import com.peanut.util.http.HttpRequestUtil;
import com.peanut.util.ocs.OCSCache;

/**
 * web工程缓存工具类
 * 
 * @author songjz
 */
public class OCSCacheWebUtil {
  private static int user_exp = OCSWebKeys.PEANUT_WEB_USER_EXP;

  /**
   * 设置用户信息到缓存中，包含：请求IP和user信息
   * 
   * @param request
   * @param user
   */
  public static void cacheUser(HttpServletRequest request, User user) {
    String ip = HttpRequestUtil.getIp(request);
    OCSCache.set(getUserCacheKey(request), user, user_exp);
    OCSCache.set(getLoginIpCacheKey(request), ip, user_exp);
  }

  /**
   * 从缓存中获取用户
   * 
   * @param request
   * @return
   */
  public static User getCacheUser(HttpServletRequest request) {
    // 以下是从缓存中获取user
    String userkey = getUserCacheKey(request);
    String loginipKey = getLoginIpCacheKey(request);
    Object user = OCSCache.get(userkey);
    if (user == null) {
      deleteCacheUser(request);
      return null;
    }
    OCSCache.getAndTouch(userkey, user_exp);
    OCSCache.getAndTouch(loginipKey, user_exp);
    return (User) user;
  }

  /**
   * 删除缓存中得用户信息，包含：请求IP和user信息
   * 
   * @param request
   */
  public static void deleteCacheUser(HttpServletRequest request) {
    OCSCache.delete(getUserCacheKey(request));
    OCSCache.delete(getLoginIpCacheKey(request));
  }

  /**
   * 获取缓存用户key
   * 
   * @param request
   * @return
   */
  private static String getUserCacheKey(HttpServletRequest request) {
    String key = getCacheKey(request);
    return OCSWebKeys.PEANUT_WEB_USER + key;
  }

  /**
   * 获取缓存的登录IP的key
   * 
   * @param request
   * @return
   */
  private static String getLoginIpCacheKey(HttpServletRequest request) {
    String key = getCacheKey(request);
    return OCSWebKeys.PEANUT_WEB_USER_LOGIN_IP + key;
  }

  /**
   * 将验证码放入缓存服务器
   * 
   * @param code
   *          ：验证码
   * @param bzPrefix
   *          ：业务类型前缀
   * @param request
   */
  public static void cacheVerificationCode(String code, String bzPrefix, HttpServletRequest request) {
    String key = getCacheKey(request);
    int exp = OCSWebKeys.PEANUT_WEB_CODE_EXP;
    OCSCache.set(bzPrefix + key, code, exp);
  }

  /**
   * <pre>
   * 获取缓存key 
   * 同时使用，使用token保存登录信息，优先使用token，如果获取失败则取session
   * </pre>
   * 
   * @param request
   */
  public static String getCacheKey(HttpServletRequest request) {
    String sessionId = request.getHeader("X-Auth-Token");
    if (StringUtil.isBlank(sessionId)) {
      sessionId = request.getParameter("token");
    }
    if (StringUtil.isBlank(sessionId)) {
      sessionId = request.getSession().getId();
    }
    return sessionId;
  }

}
